#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <unistd.h>

int get_tcp_fd();

int main(int argc, char *argv[])
{
    int tcp_fd = get_tcp_fd();

    int epoll_fd = epoll_create(1);
    if (epoll_fd < 0)
    {
        perror("epoll fail");
        return -1;
    }
    struct epoll_event event;
    event.data.fd = tcp_fd;
    event.events = STDIN_FILENO | EPOLLIN | EPOLLET;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, tcp_fd, &event);

    int num = 0;
    struct epoll_event events[1000];
    while (1)
    {
        num = epoll_wait(epoll_fd, &event, 1000, 6000);
        if (num < 0)
        {
            perror("epoll_wait error\n");
            return -1;
        }
        else if (num == 0)
        {
            printf("time out\n");
        }
        else
        {
            for (int i = 0; i < num; i++) // 循环处理所有的需要处理事件
            {
                int sockfd = events[i].data.fd; // 获取有事件发生的套接字对象
                if (sockfd == tcp_fd)           // 监听到客户端的连接
                {
                    struct sockaddr_in client_addr; // 准备获取连接的客户端的信息
                    socklen_t len = sizeof(client_addr);
                    memset(&client_addr, 0, len);
                    int con_fd =
                        accept(tcp_fd, (struct sockaddr *)&client_addr, &len); // 接收客户端的连接
                    if (con_fd < 0)
                    {
                        printf("accept error\n");
                        return -1;
                    }
                    // 如果接受成功：把客户端也上树，进行监听
                    struct epoll_event event;
                    event.data.fd = con_fd;
                    // 设置事件
                    event.events = EPOLLIN | EPOLLRDHUP;
                    // 上树
                    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, con_fd, &event);
                }
                else if (events[i].events & EPOLLIN) // 处理客户端套接字上的读事件
                {
                    char buf[1024] = {0};
                    printf("read is %s\n", buf);
                }
                else if (events[i].events & STDIN_FILENO) // 处理客户端套接字上的读事件
                {
                    char buf[1024] = {0};
                    scanf("%s", buf);
                    printf("stdin is %s\n", buf);
                }
            }
        }
    }

    close(tcp_fd);
    return 0;
}

int get_tcp_fd()
{
    int tcp_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (tcp_fd < 0)
    {
        perror("socket fail");
        exit(-1);
    }
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(50000);
    inet_pton(AF_INET, "0.0.0.0", &server_addr.sin_addr);

    int on = 1;
    setsockopt(tcp_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    int ret = bind(tcp_fd, (struct sockaddr *)&server_addr.sin_addr, sizeof(server_addr));

    listen(tcp_fd, 1);
    return tcp_fd;
}
